<template>
  <div>
    <div>
      <a-form-model layout="horizontal" :model="form" ref="queryForm" labelAlign="left">
        <div class="fold">
          <a-row :gutter="[24, 0]">
            <a-col :span="5">
              <a-form-model-item
              :label-col="{span: 6}"
              :wrapperCol="{span: 18, offset: 0}"
                label="标签"
                prop="label"
              >
                <a-input v-model="form.label" />
              </a-form-model-item>
            </a-col>
            <a-col :span="5">
              <a-form-model-item
              :label-col="{span: 6}"
              :wrapperCol="{span: 18, offset: 0}"
                label="状态"
                prop="status"
              >
                <a-select v-model="form.status" :getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}">
                  <a-select-option v-for="item in dict.status" :key="item.key" :value="item.value">{{item.title}}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
        </div>
      </a-form-model>
    </div>
    <div>
      <div>
        <a-button class="space-vertical" @click="showAddModal" type="primary" v-auth="`config:dict:add`">新增</a-button>
        <a-dropdown>
          <a-button class="space-vertical">批量操作 <a-icon type="down" /></a-button>
          <a-menu @click="batchAction" slot="overlay">
            <a-menu-item key="delete" v-auth="`config:dict:delete`">批量删除</a-menu-item>
          </a-menu>
        </a-dropdown>
        <a-button @click="resetForm" style="margin-left: 8px;float: right;">重置</a-button>
        <a-button @click="submitForm" type="primary" style="float: right;">查询</a-button>
      </div>
      <standard-table
        ref="table"
        :size="`small`"
        :scrollY="380"
        :page="page"
        :pageSize="pageSize"
        :total="total"
        :loading="loading"
        :columns="columns"
        :dataSource="dataSource"
        :selectedRows.sync="selectedRows"
        @onPageChange="onPageChange"
      >
        <div slot="action" slot-scope="{text, record}">
          <a @click="showEditModal(record.id)" v-auth="`config:dict:edit`">
            编辑
          </a>
          <a-divider class="row-btn-divider" type="vertical" v-auth="`config:dict:delete`"/>
          <a @click="showDeleteModal(record.id)" v-auth="`config:dict:delete`">
            删除
          </a>
        </div>
        <div slot="status" slot-scope="{text}">
          <a-badge :status="text == 1 ? 'success' : 'error'" :text="text | dictFilter(dict.status)"/>
        </div>
      </standard-table>
    </div>
    <add-modal
      ref="addModal"
      :visible="visibleAddModal"
      @cancel="hideAddModal"
      @ok="addSuccess"
    />
   <edit-modal
      ref="editModal"
      :visible="visibleEditModal"
      @cancel="hideEditModal"
      @ok="editSuccess"
    />
  </div>
</template>

<script>
import StandardTable from '@/components/table/standard-table'
import AddModal from './add-modal'
import EditModal from './edit-modal'
import {dictService} from '@/services'

const columns = [
  {
    title: '序号',
    dataIndex: 'no',
    width: 60,
    scopedSlots: { customRender: 'no' }
  },
  {
    title: '标签',
    dataIndex: 'label',
    width: 120
  },
  {
    title: '值',
    dataIndex: 'value',
    width: 120
  },
  {
    title: '排序',
    dataIndex: 'sort',
    width: 80
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 80,
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 160
  },
  {
    title: '修改时间',
    dataIndex: 'updateTime',
    width: 160
  },
  {
    title: '操作',
    width: 160,
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'Dict',
  components: { StandardTable, AddModal, EditModal },
  data () {
    return {
      loading: false,
      page: 1,
      pageSize: 10,
      total: 0,
      columns: columns,
      dataSource: [],
      selectedRows: [],
      visibleAddModal: false,
      visibleEditModal: false,
      form: {
        label: undefined,
        status: undefined,
        parentId: undefined
      },
      dict: {
        status: []
      },
    }
  },
  filters: {
    dictFilter: (val, dictList) => {
      const dict = dictList.find(item => item.value == val)
      return dict ? dict.title : '未知'
    }
  },
  authorize: {
    showAddModal: 'config:dict:add',
    showEditModal: 'config:dict:edit',
    showBatchDeleteModal: 'config:dict:delete'
  },
  methods: {
    reloadTable() {
      this.selectedRows = []
      this.page = 1
      this.queryListAction()
    },
    resetForm() {
      this.$refs.queryForm.resetFields()
      this.reloadTable()
    },
    submitForm() {
      this.reloadTable()
    },
    showAddModal() {
      this.visibleAddModal = true
      this.$nextTick(() => {
        this.$refs.addModal.form.parentId = this.form.parentId
      })
    },
    showEditModal(key) {
      this.visibleEditModal = true
      this.$refs.editModal.queryAction(key)
    },
    hideAddModal() {
      this.visibleAddModal = false
      this.$refs.addModal.$refs.form.resetFields()
    },
    hideEditModal() {
      this.visibleEditModal = false
      this.$refs.editModal.$refs.form.resetFields()
    },
    addSuccess() {
      this.hideAddModal()
      this.reloadTable()
    },
    editSuccess() {
      this.hideEditModal()
      this.reloadTable()
    },
    deleteAction(keys) {
      this.confirmLoading = true
      const params = {
        ids: keys
      }
      return dictService.del(JSON.stringify(params)).then(res => {
        const result = res.data
        if (result.code === 200) {
          this.$message.success(result.msg)
          this.selectedRows = []
          this.reloadTable()
        }
      }).finally(this.confirmLoading = false)
    },
    batchAction (e) {
      if (this.selectedRows.length <= 0) {
        this.$message.warning('请选择记录后操作')
        return
      }
      if (e.key === 'delete') {
        this.showBatchDeleteModal()
      }
    },
    showDeleteModal (key) {
      this.$confirm({
        confirmLoading: this.confirmLoading,
        icon: 'info-circle',
        title: '警告',
        content: '你确定要删除此项吗？',
        okType: 'danger',
        onOk:() => {
          this.deleteAction([key])
        },
        onCancel() {},
      })
    },
    showBatchDeleteModal () {
      this.$confirm({
        confirmLoading: this.confirmLoading,
        icon: 'info-circle',
        title: '警告',
        content: '你确定要删除所有选中项吗？',
        okType: 'danger',
        onOk:() => {
          this.deleteAction(this.selectedRows.map(item => item.id))
        },
        onCancel() {},
      })
    },
    onPageChange(pagination) {
      this.page = pagination.current
      this.pageSize = pagination.pageSize
      this.queryListAction()
    },
    queryListAction() {
      this.loading = true
      const params = {
        page: this.page,
        pageSize: this.pageSize,
        queryParams: this.form
      }
      dictService.queryList(JSON.stringify(params)).then(res => {
        const result = res.data
        if (result.code === 200) {
          this.dataSource = []
          this.dataSource = result.data.records
          this.total = result.data.totalCount
        }
      }).finally(this.loading = false)
    },
    setParentId(val) {
      this.form.parentId = val
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.getDict(JSON.stringify({code: 'SYS_STATUS'})).then(res => this.dict.status = res.data.data)
      this.reloadTable()
    })
  }
}
</script>
<style scoped lang="less">
  .ant-form-item {
    margin-bottom: 12px;
  }
  .fold{
    width: calc(100% - 12px);
    display: inline-block
  }
  @media screen and (max-width: 900px) {
    .fold {
      width: 100%;
    }
  }
</style>